package com.zee.home.interceptor;

import com.zee.common.exception.ExceptionCast;
import com.zee.common.utils.TimeConvertUtil;
import com.zee.home.annotation.Login;
import com.zee.home.entity.UserToken;
import com.zee.home.model.response.HomeCode;
import com.zee.home.service.IUserTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Api权限(Token)验证
 *
 * @author Mark LinZee
 * @email LinZee666@163.com
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private IUserTokenService userTokenService;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }

        //token为空
        if (StringUtils.isBlank(token)) {
            ExceptionCast.cast(HomeCode.TOKEN_NOT_EMPTY);
        }

        //查询token信息
        UserToken userToken = userTokenService.getByToken(token);
        if (userToken == null || TimeConvertUtil.getMillisTime(userToken.getExpireTime()) < System.currentTimeMillis()) {
            ExceptionCast.cast(HomeCode.TOKEN_INVALID);
        }

        //设置userId到request里，后续根据@RequestAttribute("userId")注解，自动获取用户id
        request.setAttribute(USER_KEY, userToken.getUserId());

        return true;
    }
}
